package cn.henu.service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Locale;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.codehaus.jackson.map.SerializationConfig;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.support.TransactionTemplate;

import cn.henu.commons.BaseService;
import cn.henu.util.ConfigUtil;
import cn.henu.util.JsonRender;
import cn.henu.util.XmlRender;

public class UserBaseService extends BaseService {

    protected static final String DSP_USER_AGENT = "DSP Business Client/1.0";

    protected static FastDateFormat dateFormater = FastDateFormat.getInstance("yyyy-MM-dd",
            Locale.SIMPLIFIED_CHINESE);

    /**
     * 配置项读取类
     */
    protected static Configuration config;

    private static String systemAuditUserName;

    static {
        config = ConfigUtil.addConfig("config");
        //config = ConfigUtil.addConfig("config_supplier");

        systemAuditUserName = config.getString("dsp.system.audit.user_name", "system");

    }

    public static Configuration getConfig() {
        return config;
    }

    public static String getSystemAuditUserName() {
        return systemAuditUserName;
    }

    @Autowired
    protected TransactionTemplate transactionTemplate;

    public TransactionTemplate getTransactionTemplate() {
        return transactionTemplate;
    }

    /**
     * xml 或 json 响应的默认编码
     */
    protected static String encoding = "UTF-8";

    /**
     * XML 字符串生成器
     */
    @Autowired
    private XmlRender xmlRender;

    /**
     * json 字符串生成器
     */
    @Autowired
    private JsonRender jsonRender;

    /**
     * 返回转换 xml 的工具对象
     * 
     * @return
     */
    public XmlRender getXmlRender() {
        xmlRender.setEncoding(encoding);
        return xmlRender;
    }

    /**
     * 返回转换 json 工具对象
     * 
     * @return
     */
    public JsonRender getJsonRender() {
        jsonRender.setEncoding(encoding);
        jsonRender.getObjectMapper().configure(SerializationConfig.Feature.INDENT_OUTPUT, false);
        return jsonRender;
    }

    /**
     * 返回 json 格式的成功或错误信息
     * 
     * @param isSuccess true 表示成功消息 false 表示错误消息
     * @param msg
     * @return
     */
    protected String getJsonMsg(Boolean isSuccess, String msg) {
        StringBuffer result = new StringBuffer("");

        if (isSuccess) {
            if (StringUtils.isBlank(msg)) {
                msg = "ok";
            }
            result.append("{\"success\":\"").append(msg).append("\"}");
        } else {
            if (StringUtils.isBlank(msg)) {
                msg = "failed";
            }
            result.append("{\"error\":\"").append(msg).append("\"}");
        }

        return result.toString();
    }

    /**
     * 返回 chartXML 格式的成功或错误信息
     * 
     * @param isSuccess true 表示成功消息 false 表示错误消息
     * @param msg
     * @return
     */
    protected String getXmlMsg(Boolean isSuccess, String msg) {

        StringBuffer result = new StringBuffer("");

        if (isSuccess) {
            if (StringUtils.isBlank(msg)) {
                msg = "ok";
            }
            result.append("<chart><success>").append(msg).append("</success></chart>");
        } else {
            if (StringUtils.isBlank(msg)) {
                msg = "failed";
            }
            result.append("<chart><error>").append(msg).append("</error></chart>");
        }

        return result.toString();
    }

    /**
     * 是否自动通过审核
     * 
     * @return 自动通过审核 true; 需要人工审核 false
     */
    public Boolean isAutoAudit() {
        return true;
    }

    /**
     * 把 Map 中的 Object 对象转换成可 显示字符串
     * 
     * @param val
     * @return
     */
    protected String convertMapValue(Object val) {
        String result = "";

        if (val instanceof Long || val instanceof Integer || val instanceof String) {

            result = String.valueOf(val);

        } else if (val instanceof Float || val instanceof Double) {

            Double d = (Double) val;

            BigDecimal bd = new BigDecimal(d);

            int scale = bd.scale();

            scale = scale > 0 ? 2 : 0;

            bd = bd.setScale(scale, BigDecimal.ROUND_HALF_UP);

            StringBuffer tempValue = new StringBuffer();
            tempValue.append(bd.toString());

            //没有小数位数的，末尾添加
            if (tempValue.toString().indexOf(".") == -1) {
                tempValue.append(".00");

            }

            result = tempValue.toString();

        } else if (val instanceof BigDecimal) {

            // BigDecimal scale 属性是小数位数，有则说明是小数，否则可能是整型

            BigDecimal bd = (BigDecimal) val;

            int scale = bd.scale();

            scale = scale > 0 ? 2 : 0;

            bd = bd.setScale(scale, BigDecimal.ROUND_HALF_UP);

            result = bd.toString();

        } else if (val instanceof Date) {

            Date dt = (Date) val;

            DateTime d = new DateTime(dt.getTime());

            if (d.getHourOfDay() == 0 && d.getMinuteOfHour() == 0 && d.getSecondOfMinute() == 0) {
                result = FastDateFormat.getInstance("yyyy-MM-dd").format(dt);
            } else {
                result = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss").format(dt);
            }

        } else {

            if (null != val) {
                result = (String) val;
                log.warn("convertMapValue()无法转换的对象: " + val.getClass().getName());
            }

        }

        if (StringUtils.isBlank(result) || "null".equalsIgnoreCase(result)) {
            return result;
        }

        return result;
    }

}
